package cn.smile.config.shiro.realm;

import cn.smile.config.shiro.CasPathConfig;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * 自定义Realm
 *
 * @Author: MaoSuyu
 * @User：John
 * @Date: 2019/7/16
 * @Time: 12:10
 * @Description: No Description
 */
@Log4j2
public class MyCasRealm extends CasRealm {

    public MyCasRealm() {
        //CAS服务器地址，去该地址验证TGT（票根）
        this.setCasServerUrlPrefix(CasPathConfig.CAS_SERVER_URL_PREFIX);
        //项目中CAS过滤器的地址
        this.setCasService(CasPathConfig.SHIRO_SERVER_URL_PREFIX + CasPathConfig.CAS_FILTER_URL_PATTERN);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("*************账号登录验证***************");
        SimpleAuthenticationInfo authenticationInfo = (SimpleAuthenticationInfo) super.doGetAuthenticationInfo(token);
        String currentUserId = authenticationInfo.getPrincipals().getPrimaryPrincipal().toString();
        if ("70000281".equals(currentUserId)) {
            throw new LockedAccountException("Test onAccessDenied");
        }
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("*************账号权限验证***************");
        String currentUserId = principals.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if ("70000281".equals(currentUserId)) {
            authorizationInfo.addStringPermission("hello");
        }
        return authorizationInfo;
    }


}
